#include <iostream>
#include <set>

using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
 
class Solution
{
public:
    ListNode* detectCycle(ListNode* head)
    {
        set<ListNode*> s;
        ListNode* cur = head;

        while (cur)
        {
            auto ret = s.insert(cur);
            if (ret.second == 0)
                return cur;
            cur = cur->next;
        }
        return nullptr;
    }
};

void test01()
{

}

int main()
{
    test01();
    return 0;
}